#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import base64
import json
import time
import random
import hashlib
from collections import OrderedDict
from datetime import timedelta, datetime
from time import localtime, strftime
from demjson import encode


class Utils:

    @staticmethod
    def base64_to_img(text, file_name):
        """
        base64 转 图片
        :param text: Base64传入
        :param file_name: 保存的名称
        :return: 保存图片
        """
        # 项目路径
        project_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
        img_data = base64.b64decode(text)
        try:
            file = open(os.path.join(project_path, "other", "images", str(file_name) + ".jpg"), "wb")
            file.write(img_data)
            file.close()
        except Exception:
            raise ValueError('保存失败')

    @staticmethod
    def img_to_base64(file_name, headers=False):
        """
        图片 转 BASE64
        :param file_name: 文件存放在other/images 传入文件名包含格式
        :param headers: 是否需要 data:image/png;base64,
        :return:
        """
        # file = open(file_name, "rb")
        # base64_data = "data:image/png;base64," + str(base64.b64encode(file.read())).replace("b'", '').replace("'", '')
        # return base64_data
        project_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
        file_path = os.path.join(project_path, "other", "images", str(file_name))
        try:
            file = open(file_path, "rb")
            base64_data = str(base64.b64encode(file.read())).replace("b'", '').replace("'", '')
            if headers:
                base64_data += "data:image/png;base64,"
            file.close()
            return base64_data
        except FileNotFoundError:
            raise FileNotFoundError('请确保/other/images/下存在该文件')

    @staticmethod
    def jwt_decode(token_jwt='Bearer eyJ0eXAiOiJ..'):
        """
        将Jwt解析，返回payload里面的内容，payload包含
        sub,iss,aud,jti,iat,nbf,exp,user_id,member_id
        :param token_jwt:
        :return: 返回dict类型的 payload
        """
        try:
            token_jwt = str(token_jwt).split('.')[1] + '=='
            payload = str(base64.b64decode(token_jwt, validate=True))
            # print(payload)
            payload = json.loads(payload.lstrip('b\'').rstrip('\''))
        except Exception:
            raise ValueError("Jwt_Token解析失败，请检查")

        return payload

    @staticmethod
    def get_random_datetime():
        """
        随机生成一个2019年到2020年的日期
        :return: string 类型时间
        """
        a1 = (2019, 1, 1, 0, 0, 0, 0, 0, 0)  # 设置开始日期时间元组（1976-01-01 00：00：00）
        a2 = (2020, 12, 31, 23, 59, 59, 0, 0, 0)  # 设置结束日期时间元组（1990-12-31 23：59：59）
        start = time.mktime(a1)  # 生成开始时间戳
        end = time.mktime(a2)  # 生成结束时间戳
        # 随机生成10个日期字符串
        t = random.randint(int(start), int(end))  # 在开始和结束时间戳中随机取出一个
        date_tuple = time.localtime(t)  # 将时间戳生成时间元组
        date = time.strftime("%Y-%m-%d %H:%M:%S", date_tuple)  # 将时间元组转成格式化字符串（1976-05-21）
        return date

    @staticmethod
    def get_current_datetime(time_type='s'):
        """
        :param: time_type s:年-月-日 时:分:秒  m:年-月-日 时:分   D:年-月-日  M:年-月 Y:年
        :return: string 类型时间
        """
        date_tuple = time.localtime()  # 将时间戳生成时间元组
        if time_type == 's':
            date = time.strftime("%Y-%m-%d %H:%M:%S", date_tuple)
        elif time_type == 'm':
            date = time.strftime("%Y-%m-%d %H:%M", date_tuple)
        elif time_type == 'D':
            date = time.strftime("%Y-%m-%d", date_tuple)
        elif time_type == 'M':
            date = time.strftime("%Y-%m", date_tuple)
        elif time_type == 'Y':
            date = time.strftime("%Y", date_tuple)
        else:
            raise ValueError('输入的类型错误，注意区分大小写！')

        return date

    @staticmethod
    def get_calculate_datetime(day):
        """
        几天后的日期
        :param: to_day 几天后或几天前的时间，传入 整数
        :return: string 类型时间
        """
        if type(day) == int:
            date = (datetime.now() + timedelta(days=day)).strftime("%Y-%m-%d")
            return date
        else:
            raise ValueError("day 类型错误")

    @staticmethod
    def get_params(text):
        """
        :param text: 机票平台订单编号：${ordersn}，第三方订单编号：${air_id}
        :return: ['ordersn', 'air_id']
        """
        params = []
        for items in text.split('$'):
            if items.startswith('{'):
                end_index = items.find('}')
                param_one = items[1:end_index]
                params.append(param_one)

        return params

    @staticmethod
    def get_random_order_no(str_len=8):
        """
        随机获得指定长度的订单号
        """
        date_tuple = time.strftime("%Y%m%d%H%M%S", time.localtime())
        rnd = str(random.randint(0, 99999999)).rjust(int(str_len), "0")
        order_no = "PY" + str(date_tuple) + "_" + rnd
        return order_no

    @staticmethod
    def get_random_num_order_no():
        """
        生成订单号:当前时间+5位随机数
        """
        date_tuple = time.strftime("%Y%m%d%H%M%S", time.localtime())
        rnd = str(random.randint(0, 99999)).rjust(5, "0")
        order_no = str(date_tuple) + rnd
        return order_no

    @staticmethod
    def get_timestamp_to_datetime(timestamp):
        """
        时间戳转日期型
        :param timestamp: 时间戳1557502800
        :return: 日期型日期
        """
        time_array = localtime(timestamp)
        date_time = strftime("%Y-%m-%d %H:%M:%S", time_array)
        return date_time

    @staticmethod
    def get_current_timestamp(time_type="s|ms"):
        """
        :return: 返回当前时间戳
        """
        if time_type == 's':
            timestamp = str(int(time.time()))
            return timestamp
        elif time_type == 'ms':
            timestamp = str(int(time.time() * 1000))
            return timestamp
        else:
            raise TypeError('请传入类型秒 s，或者 毫秒 ms')

    # 随机生成手机号
    @staticmethod
    def random_phone():
        head_list = ["130", "131", "132", "133", "134", "135", "136", "137", "138", "139",
                     "147", "150", "151", "152", "153", "155", "156", "157", "158", "159",
                     "186", "187", "188", "189"]
        phone_num = random.choice(head_list) + "".join(random.choice("0123456789") for _ in range(8))
        return phone_num

    @staticmethod
    def random_name():
        first_name = ["优凯", "长泰", "春波", "盈一", "佳丰", "彩虹", "缤纷", "大关", "盛世"]
        second_name = ["公寓", "小区", "一区", "二区", "三区", "东苑", "西苑", "南苑", "北苑"]
        name = random.choice(first_name) + random.choice(second_name) + time.strftime("%Y-%m-%d %H:%M:%S",
                                                                                      time.localtime())
        return name

    @staticmethod
    def get_address_lon_and_lat(address_name):
        """
        输入中文地方点返回经纬度坐标
        :param address_name: 地点名称如：西湖，漠河，新疆
        :return:经纬度  经度 Longitude 简写Lng 纬度 Latitude 简写Lat
        """
        # 杭州
        if address_name == '西湖':
            return '120.13026', '30.25961'
        elif address_name == '杭州四季青':
            return '120.19447924353027', '30.237866840584026'
        elif address_name == '钱江世纪城':
            return '120.255112', '30.233759'
        elif address_name == '钱塘玫瑰湾':
            return '120.14119179629517', '30.168641417078756'
        elif address_name == '奥兰多小镇':
            return '120.23829121894073', '30.163304169647624'
        elif address_name == '钱塘江':
            return '120.571609', '30.273146'
        elif address_name == '滨江区人民政府':
            return '120.21194562698366', '30.2084741749429'
        elif address_name == '中医药大学':
            return '120.15667208465575', '30.181554274400057'
        elif address_name == '浙江大学':
            return '120.19638559391785', '30.2709676762771'
        elif address_name == '拱墅区政府':
            return '120.1416708465576', '30.31914727092131'
        elif address_name == '杭州市第二人民医院':
            return '120.14141335449217', '30.322073835889082'
        elif address_name == '杭州半山国家森林公园':
            return '120.19492878875731', '30.363369824533493'
        elif address_name == '市民中心':
            return '120.211889', '30.245575'
        # 宁波
        elif address_name == '宁波东站':
            return '121.53720779663082', '29.860637375058744'
        elif address_name == '宁波老外滩':
            return '121.56089706665036', '29.875821106843752'
        # 上海
        elif address_name == '上海东方明珠':
            return '121.65736936441805', '31.584551988445074'
        elif address_name == '上海市浦东机场':
            return '121.806282', '31.150347590938047'
        # 北京
        elif address_name == '北京天安门':
            return '116.39748509325408', '39.90877985134003'
        elif address_name == '北京鸟巢':
            return '116.23128', '40.22077'
        # 武汉
        elif address_name == '武汉华中科技大学':
            return '114.42084059922793', '30.513714348655597'
        elif address_name == '武汉市武汉大学':
            return '114.35459877378847', '30.553329975198462'
        # 广州
        elif address_name == '广州市冼村':
            return '113.335701', '23.124885200722403'
        elif address_name == '哈尔滨工业大学':
            return '126.63240616931151', '45.74356603432537'
        elif address_name == '乌鲁木齐':
            return '88.31095416931151', '43.363530400798275'
        elif address_name == '漠河':
            return '122.53864', '52.97209'
        # 云南
        elif address_name == '西双版纳':
            return '100.797390', '22.007490'
        elif address_name == '大理':
            return '100.26764', '25.60648'
        # 其他
        elif address_name == '海南省海口市':
            return '110.337952', '20.052389'
        elif address_name == '香港':
            return '114.16546', '22.27534'
        elif address_name == '台湾':
            return '121.49478424999998', '25.01399596530737'
        elif address_name == '东沙群岛':
            return '25.01399596530737', '21.04150058184896'
        elif address_name == '非洲':
            return '19.574618234374988', '11.456400388834757'
        elif address_name == '北冰洋':
            return '70.90274323437498', '80.31606560843721'
        elif address_name == '老挝':
            return '103.06521882031248', '22.13710011414033'
        elif address_name == '海南省海口市龙华区':
            return '110.337952', '20.052389'
        elif address_name == '杭州萧山机场':
            return '120.432414', '30.234708'

        else:
            raise ValueError('输入的地址错误')


if __name__ == '__main__':
    pass
